package com.atguigu.day04;

import com.atguigu.bean.WaterSensor;
import com.atguigu.func.WaterSensorMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author Felix
 * @date 2024/7/12
 * 该案例演示了通过侧输出流实现分流效果
 * 需求：将WaterSensor按照Id类型进行分流
 */
public class Flink04_Split_Stream_SideOutPut {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        Configuration conf = new Configuration();
        conf.set(RestOptions.PORT,8088);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        //TODO 2.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        
        //TODO 3.对流中数据进行类型转换    String->WaterSensor对象
        SingleOutputStreamOperator<WaterSensor> mapDS = socketDS.map(new WaterSensorMapFunction());
        
        //TODO 4.分流
        //4.1 定义侧输出流标签
        OutputTag<WaterSensor> ws1Tag = new OutputTag<WaterSensor>("ws1Tag"){};
        OutputTag<WaterSensor> ws2Tag = new OutputTag<WaterSensor>("ws2Tag", Types.POJO(WaterSensor.class));
        //4.2 分流逻辑  注意：如果使用侧输出流，处理函数只能调用process，因为在process方法中，可以传递上下文对象
        SingleOutputStreamOperator<WaterSensor> splitDS = mapDS.process(
                new ProcessFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public void processElement(WaterSensor ws, ProcessFunction<WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {
                        String id = ws.getId();
                        if ("ws1".equals(id)) {
                            //将ws1数据"放到"侧输出流中
                            ctx.output(ws1Tag, ws);
                        } else if ("ws2".equals(id)) {
                            //将ws2数据"放到"侧输出流中
                            ctx.output(ws2Tag, ws);
                        } else {
                            //如果传感器的id不是ws1，也不是ws2，将数据放到主流中
                            out.collect(ws);
                        }
                    }
                }
        );

        //TODO 5.将不同流的数据进行打印
        splitDS.print("主流");
        SideOutputDataStream<WaterSensor> ws1DS = splitDS.getSideOutput(ws1Tag);
        SideOutputDataStream<WaterSensor> ws2DS = splitDS.getSideOutput(ws2Tag);
        ws1DS.print("侧流ws1").setParallelism(2);
        ws2DS.print("侧流ws2").setParallelism(3);

        //TODO 6.提交作业
        env.execute();
    }
}
